<?php

namespace app\api\controller\v41;

use app\aliyun\controller\AliyunVOD;
use app\api\controller\v13\Auth2;
use app\common\cachemodel\zl6\Zl6Meditation;
use app\common\cachemodel\zl6\Zl6MeditationPlayRecord;
use app\common\cachemodel\zl6\Zl6MeditationSection;
use app\common\cachemodel\zl6\Zl6MeditationSubscribe;
use app\common\cachemodel\zl6\Zl6MeditationTodayPlayDuration;
use app\common\cachemodel\ZlcrTag;
use app\common\cachemodel\ZlUserVip;
use think\response\Json;

class UserMeditate extends Auth2
{
    /**
     * 冥想播放列表
     * @return Json
     * @throws \Exception
     */
    public function getPlayList()
    {
        $id = input('id/d', 0);
        $chapterId = input('chapter_id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        $zl6MeditationModel = new Zl6Meditation();
        $zlcrTagModel = new ZlcrTag();
        $zl6MeditionSectionModel = new Zl6MeditationSection();
        $meditationInfo = $zl6MeditationModel->getInfoById($id, ['category_type', 'ability_tids', 'cate_tid', 'title', 'lottie', 'is_vip_free', 'price', 'start_time']);
        if (!$meditationInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        if ($meditationInfo['category_type'] === 1)
        {   // 12星座
            if ($chapterId === 0)
            {
                $signId = 1;
            } else
            {
                $sectionInfo = $zl6MeditionSectionModel->getInfoById($chapterId, ['cid', 'sign_id']);
                if ($sectionInfo && $sectionInfo['cid'] === $id)
                {
                    $signId = $sectionInfo['sign_id'];
                } else
                {
                    $signId = 1;
                }
            }
        } else
        {
            $signId = 0;
        }
        $mType = $meditationInfo['category_type'] === 1 ? 2 : 1;   // 课程类型 1=>普通课程 2=>十二星座课程

        if ($meditationInfo['is_vip_free'] === 1)
        {   // 支持vip免费
            $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
            $isVipUnlock = $vipLevel > 0;   // 是否是VIP    是则解锁
        }
        if ((float)$meditationInfo['price'] <= 0)
        {   // 免费
            $isVipUnlock = true; // 免费 自动判断解锁
        }
        $chapterListData = $zl6MeditionSectionModel->getSectionPlayUnlockListData($id, $mType, $this->user['id'], $signId, $isVipUnlock ?? false);
        if ($meditationInfo['start_time'] > 0 && $this->request->time() < $meditationInfo['start_time'])
        {   //  未开始
            $chapterListData['list'] = [];
        }
        $tagIds = $meditationInfo['ability_tids'];
        $tagIds[] = $meditationInfo['cate_tid'];
        $tagListInfo = $zlcrTagModel->batchGetInfoByIds($tagIds);
        $tagList = [];
        if (isset($tagListInfo[$meditationInfo['cate_tid']]) && $tagListInfo[$meditationInfo['cate_tid']])
        {
            $tagList[] = [
                'name' => $tagListInfo[$meditationInfo['cate_tid']]['tag_name'],
                'icon' => $tagListInfo[$meditationInfo['cate_tid']]['templet_url'],
            ];
        }
        foreach ($meditationInfo['ability_tids'] as $tid)
        {
            if (isset($tagListInfo[$tid]) && $tagListInfo[$tid])
            {
                $tagList[] = [
                    'name' => $tagListInfo[$tid]['tag_name'],
                    'icon' => $tagListInfo[$tid]['templet_url'],
                ];
            }
        }
        if ($meditationInfo['is_vip_free'] === 1 && $chapterListData['status'] === 0)
        {
            $recommendVip = [
                'title' => '小行星会员',
                'desc' => '开通后即可免费参与新月许愿、水逆影响减弱等定期活动。',
                'btn_name' => '开通会员',
            ];
        }

        if ($chapterListData['list'])
        {   // 只有 可播放的章节 信息 才获取播放签名信息    4小时 有效期
            $stsSign = (new AliyunVOD())->getStsToken($this->headers['app-type'], 3600);
        }

        $resData = [
            'title' => $meditationInfo['title'],
            'tag_list' => $tagList,
            'chapter_list' => $chapterListData['list'],
            'recommend_vip' => $recommendVip ?? null,
            'sts_sign' => $stsSign ?? '',
            'bg_url' => $meditationInfo['lottie'],
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 冥想播放进度更新
     * @return Json
     * @throws \Exception
     */
    public function setPlayProgress()
    {
        $chapterId = input('chapter_id/d', 0);
        $status = input('status/d', 0);
        $cid = input('cid/d', 0);
        if (!$chapterId || !in_array($status, [1, 2], true) || ($status === 2 && !$cid))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if ($status === 1)
        {
            $cid = 0;
        }
        $zl6MeditionSectionModel = new Zl6MeditationSection();
        $zl6MeditationPlayRecordModel = new Zl6MeditationPlayRecord();
        $sectionInfo = $zl6MeditionSectionModel->getInfoById($chapterId, ['id', 'cid']);

        if (!$sectionInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $date = (int)date('Ymd');
        if ($status === 2)
        {   // 继续 播放    更新播放记录 及 每日播放时长
            $playRecodeInfo = $zl6MeditationPlayRecordModel->getInfoById($cid);
            if (!$playRecodeInfo || $playRecodeInfo['uid'] !== $this->user['id'] || $playRecodeInfo['sid'] !== $chapterId)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            // 更新 播放时长
            // 计算 增加播放时长
            $incDuration = $this->request->time() - $playRecodeInfo['end_time'];
            if ($incDuration >= 120)
            {
                return show(config('code.success'), '请求成功', ['cid' => $cid]);
            }
            $zl6MeditationPlayRecordModel->UpdateData($cid, [
                'duration' => $playRecodeInfo['duration'] + $incDuration,
                'end_time' => $this->request->time(),
            ]);
            // 更新今日播放时长信息
            (new Zl6MeditationTodayPlayDuration())->setTodayPlayDuration($this->user['id'], $date, $incDuration, 0, 0);
        } else
        {   // 开始播放  只写入 播放记录 不记录每日播放时长
            $data = [
                'uid' => $this->user['id'],
                'mid' => $sectionInfo['cid'],   // 冥想课程ID
                'sid' => $chapterId,    // 冥想课程章节ID
                'duration' => 0,
                'start_time' => $this->request->time(),
                'end_time' => $this->request->time(),
            ];
            // 开始 播放
            $cid = $zl6MeditationPlayRecordModel->SaveData($data);

            $nowTime = time();
            $meditationInfo = (new Zl6Meditation())->getInfoById($sectionInfo['cid'], ['category_type', 'start_time', 'end_time']);
            $isCrescent = 0;
            $isBadLuck = 0;
            if ($meditationInfo['end_time'] > 0 && $meditationInfo['start_time'] < $nowTime && $meditationInfo['end_time'] > $nowTime)
            {   // 进行中 冥想课程
                if ($meditationInfo['category_type'] === 2) // 1=>十二星座， 2=>新月， 3=>水逆
                {
                    $isCrescent = 1;
                } elseif ($meditationInfo['category_type'] === 3)
                {
                    $isBadLuck = 1;
                }
            }
            // 更新今日播放时长信息
            (new Zl6MeditationTodayPlayDuration())->setTodayPlayDuration($this->user['id'], $date, 0, $isCrescent, $isBadLuck);
        }

        if ($cid)
        {
            return show(config('code.success'), '请求成功', ['cid' => $cid]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试');
        }
    }

    /**
     * 我的冥想
     * @return Json
     * @throws \Exception
     */
    public function myInfo()
    {
        $date = input('date/s', '');
        if (empty($date))
        {
            return show(config('code.error'), '服务异常，请选择月份！');
        }
        // 获取月份的时间戳
        $dateStimestamp = strtotime($date);
        if ($date !== date('Y-m', $dateStimestamp))
        {
            return show(config('code.error'), '服务异常，日期格式错误！');
        }
        // 获取今日的日期
        $todayDate = (int)date('Ymd');
        $zl6MeditionTodayPlayDurationModel = new Zl6MeditationTodayPlayDuration();
        if ($this->user)
        {
            // 获取 今天 之前统计的总时长信息 - 不包含今日信息
            $totalData = $zl6MeditionTodayPlayDurationModel->getPlayDurationTotalData($this->user['id'], $todayDate);
            // 获取 今天 的冥想信息
            $todayDurationData = $zl6MeditionTodayPlayDurationModel->getTodayPlayDuration($this->user['id'], $todayDate);
        } else
        {
            $totalData = ['total_duration' => 0, 'total_day' => 0, 'max_continuous_day' => 0, 'crescent_day' => 0, 'bad_luck_day' => 0,];
            $todayDurationData = [];
        }
        if ($todayDurationData)
        {
            // 秒转分钟 向上取整
            $todayMinute = ceil($todayDurationData['duration'] / 60);
            // 秒转分钟 向上取整
            $totalMinute = ceil(($totalData['total_duration'] + $todayDurationData['duration']) / 60);
            $totalDay = $totalData['total_day'] + 1;
            $maxMunningDays = max($totalData['max_continuous_day'], $todayDurationData['continuous_day']);
            $crescentNum = $todayDurationData['is_crescent'] === 1 ? $totalData['crescent_day'] + 1 : $totalData['crescent_day'];
            $badLuckNum = $todayDurationData['is_bad_luck'] === 1 ? $totalData['bad_luck_day'] + 1 : $totalData['bad_luck_day'];
        } else
        {
            $todayMinute = 0;
            $totalMinute = ceil($totalData['total_duration'] / 60);
            $totalDay = $totalData['total_day'];
            $maxMunningDays = $totalData['max_continuous_day'];
            $crescentNum = $totalData['crescent_day'];
            $badLuckNum = $totalData['bad_luck_day'];
        }
        $monthInt = (int)date('Ym', $dateStimestamp);
        $meditateData = $this->user ? $zl6MeditionTodayPlayDurationModel->getPlayDurationMonthData($this->user['id'], $monthInt) : [];
        if ($totalMinute >= 1000)
        {
            $totalTime = ceil($totalMinute / 60);
            if ($totalTime >= 1000)
            {
                $totalTime = ceil($totalTime / 24);
                $totalTimeUnit = '天';
            } else
            {
                $totalTimeUnit = '小时';
            }
        } else
        {
            $totalTime = $totalMinute;
            $totalTimeUnit = '分钟';
        }

        $resData = [
            'today_minute' => $todayMinute,
            'total_time' => $totalTime,
            'total_time_unit' => $totalTimeUnit,
            'total_day' => $totalDay,
            'max_running_days' => $maxMunningDays,
            'tip' => "已累计参加新月许愿{$crescentNum}次，水逆弱化冥想{$badLuckNum}次",
            'meditate_data' => $meditateData,
            'crescent_num' => $crescentNum,
            'bad_luck_num' => $badLuckNum,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 冥想记录
     * @return Json
     * @throws \Exception
     */
    public function getRecordList()
    {
        $page = input('page/d', 1);
        if ($page <= 0)
        {
            $page = 1;
        }
        $zl6MeditionPlayRecordModel = new Zl6MeditationPlayRecord();
        $zl6MeditationModel = new Zl6Meditation();
        $zl6MeditionSectionModel = new Zl6MeditationSection();
        $zlcrTagModel = new ZlcrTag();
        $playRecordPageList = $zl6MeditionPlayRecordModel->getPlayRecordPageDataIds($this->user['id'], $page);
        $resData = [];
        foreach ($playRecordPageList['data'] as $mid => $recordId)
        {
            $recordId = (int)round($recordId);
            $recordInfo = $zl6MeditionPlayRecordModel->getInfoById($recordId, ['sid']);
            $meditationInfo = $zl6MeditationModel->getInfoById($mid, ['ability_tids', 'cate_tid', 'desc', 'type', 'title', 'cover_img', 'category_type']);
            $sectionInfo = $zl6MeditionSectionModel->getInfoById($recordInfo['sid'], ['id', 'title', 'sign_id']);
            $tagIds = $meditationInfo['ability_tids'];
            if ($meditationInfo['cate_tid'])
            {
                $tagIds[] = $meditationInfo['cate_tid'];
            }
            $tagListInfo = $zlcrTagModel->batchGetInfoByIds($tagIds);
            $tagList = [];
            if (isset($meditationInfo['cate_tid']) && $meditationInfo['cate_tid'] && isset($tagListInfo[$meditationInfo['cate_tid']]) && $tagListInfo[$meditationInfo['cate_tid']])
            {
                $tagList[] = [
                    'name' => $tagListInfo[$meditationInfo['cate_tid']]['tag_name'],
                    'bg_color' => $tagListInfo[$meditationInfo['cate_tid']]['extend']['bg_color'] ?? '',
                    'color' => $tagListInfo[$meditationInfo['cate_tid']]['extend']['txt_color'] ?? '',
                ];
            }
            foreach ($meditationInfo['ability_tids'] as $tid)
            {
                if (isset($tagListInfo[$tid]) && $tagListInfo[$tid])
                {
                    $tagList[] = [
                        'name' => $tagListInfo[$tid]['tag_name'],
                        'bg_color' => $tagListInfo[$tid]['extend']['bg_color'] ?? '',
                        'color' => $tagListInfo[$tid]['extend']['txt_color'] ?? '',
                    ];
                }
            }
            $desList = $meditationInfo['desc'] ? [$meditationInfo['desc']] : [];
            $desList[] = $meditationInfo['type'] === 1 ? '大众冥想' : '半定制冥想';
            if ($meditationInfo['category_type'] === 1)
            {   // 十二星座 默认选中上次 播放的星座列表
                $signId = $sectionInfo['sign_id'];
            } else
            {
                $signId = 0;    // 星座ID
            }
            $resData[] = [
                'id' => $mid,
                'title' => $meditationInfo['title'],
                'img' => $meditationInfo['cover_img'],
                'tag_list' => $tagList,
                'desc' => $desList,
                'record_data' => [
                    'chapter_id' => $sectionInfo['id'],
                    'title' => $sectionInfo['title'],
                ],
                'target' => 'local',
                'link' => "meditate_detail?id={$mid}&sign={$signId}&need_auth=0",
            ];
        }

        $playRecordPageList['data'] = $resData;

        return show(config('code.success'), '请求成功', $playRecordPageList);
    }

    /**
     * 冥想预约接口
     * @return Json
     * @throws \Exception
     */
    public function setSubscribe()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        if (!$id || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zl6MeditationModel = new Zl6Meditation();
        $zl6MeditationSubscribeModel = new Zl6MeditationSubscribe();
        $meditationInfo = $zl6MeditationModel->getInfoById($id, ['start_time', 'end_time', 'sub_num']);
        if (!$meditationInfo || $meditationInfo['end_time'] === 0)
        {   // 结束时间为0
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        if ($meditationInfo['start_time'] <= $this->request->time())
        {
            return show(config('code.error'), '活动已经开始了，预约提醒失败～');
        }
        // 获取当前预约状态
        $subId = $zl6MeditationSubscribeModel->isSubscribe($this->user['id'], $id);
        if ($type === 1)
        {   // 预约
            if ($subId)
            {   // 已经预约了
                return show(config('code.success'), '预约成功');
            }
            $data = [
                'uid' => $this->user['id'],
                'mid' => $id,
                'is_send' => 0,
                'create_time' => $this->request->time(),
            ];
            $res = $zl6MeditationSubscribeModel->SaveData($this->user['id'], $data);
            if ($res)
            {
                // 增加订阅数
                $zl6MeditationModel->UpdateData($id, ['sub_num' => $meditationInfo['sub_num'] + 1]);

                return show(config('code.success'), '预约成功');
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试');
            }
        } else
        {   // 取消预约
            if (!$subId)
            {
                return show(config('code.success'), '取消预约成功');
            }
            $res = $zl6MeditationSubscribeModel->delData($subId, $id, $this->user['id']);
            if ($res)
            {
                return show(config('code.success'), '取消预约成功');
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试');
            }
        }
    }
}